const gulp = require('gulp');
const less = require('gulp-less');
const minifyCSS = require('gulp-csso');
const terser = require('gulp-terser');
const { spawn } = require('child_process');

gulp.task('js', async () => {
    return gulp.src('js/**/*.js')
        .pipe(terser())
        .pipe(gulp.dest('dist/js'))
});
gulp.task('css', async () => {
    return gulp.src('less/**/*.less')
        .pipe(less())
        .pipe(minifyCSS())
        .pipe(gulp.dest('dist/css'))
});

gulp.task('build-version', (cb) => {
    const node = spawn('node', ['build.js'], { cwd: process.cwd(), stdio: 'inherit' });
    node.on('close', (code) => {
        if (code === 0) {
            console.log('Build version completed successfully');
            cb();
        } else {
            console.error('Build version failed with code:', code);
            cb(new Error('Build version failed'));
        }
    });
});

gulp.task('watch', async () => {
    gulp.watch('js/**/*.js', gulp.series('js'));
    gulp.watch('less/**/*.less', gulp.series('css'));
    // 监听HTML文件变化并触发版本号添加任务，但排除dist目录中的文件
    gulp.watch(['*.html', '!dist/**/*.html'], gulp.series('build-version'));
});